<template>
    <transition appear name="animate__animated animate__bounce" enter-active-class="animate__fadeIn">
        <el-container>
            <el-main class="addArticel">
                <client-only>
                    <el-row :gutter="20">
                        <el-col :span="20">
                            <el-input type="text" placeholder="请输入文章标题...." v-model="article.title" maxlength="10"
                                show-word-limit class="blog-titel">
                            </el-input>
                        </el-col>
                        <el-col :span="4">
                            <el-button type="primary" @click="openDialog(0)" plain>草稿箱</el-button>
                            <el-button type="primary" @click="openDialog(1)">发布</el-button>
                        </el-col>
                    </el-row>
                    <mavon-editor v-model="article.content" @imgAdd="handleImgAdd" ref="md"></mavon-editor>

                    <!-- 发布对话框 -->
                    <el-dialog title="文章发布" :visible.sync="dialogFormVisible" :modal="false">
                        <el-form :model="article" style="width: 100%;" :rules="rules">
                            <el-form-item label="文章封面：" :label-width="formLabelWidth">
                                <el-upload class="avatar-uploader" :action="uploadUrl" :show-file-list="false"
                                    :on-success="(res, file) => { return handleAvatarSuccess(res, file) }">
                                    <img v-if="article.cover" :src="article.cover" class="avatar">
                                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                </el-upload>
                            </el-form-item>
                            <el-form-item label="文章分类：" :label-width="formLabelWidth" prop="type">
                                <el-select v-model="article.type" placeholder="文章分类" style="width: 100%;">
                                    <el-option v-for="item in articleTypeList" :key="item.id" :label="item.name"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="可见范围：" :label-width="formLabelWidth" prop="lookScope">
                                <template>
                                    <el-radio-group v-model="article.lookScope" prop="text">
                                        <el-radio :label="item.value" v-for="item in lookScopeList" :key="item.id"
                                            border size="medium">
                                            {{ item.name }}
                                        </el-radio>
                                    </el-radio-group>
                                </template>
                            </el-form-item>
                            <el-form-item label="文章摘要：" :label-width="formLabelWidth" prop="digest">
                                <el-input type="textarea" placeholder="请输入摘要" v-model="article.digest" maxlength="100"
                                    show-word-limit>
                                </el-input>
                            </el-form-item>
                        </el-form>
                        <div slot="footer" class="dialog-footer">
                            <el-button @click="dialogFormVisible = false">取 消</el-button>
                            <el-button type="primary" @click="submitFrom()">确 定</el-button>
                        </div>
                    </el-dialog>
                </client-only>
            </el-main>
        </el-container>
    </transition>
</template>

<script>
import BlogHeader from '~/pages/layouts/BlogHeader.vue';
import BlogFooter from '~/pages/layouts/BlogFooter.vue';
import dict from '~/api/dict';
import articleApi from '~/api/article'
export default {
    transition: 'fade',
    components: { BlogHeader, BlogFooter },
    data() {
        return {
            uploadUrl: 'http://127.0.0.1:8203/local/upload',
            article: {
                digest: ''
            }, // 文章实体
            lookScopeList: [], // 文章可见范围
            articleTypeList: [], // 文章类型
            dialogFormVisible: false,
            formLabelWidth: '120px',
            rules: {
                digest: [
                    { required: true, message: '请输入文本摘要', trigger: 'blur' },
                    { min: 0, max: 100, message: '长度在 0 到 100 个字符', trigger: 'blur' }
                ],
                type: [
                    { required: true, message: '请选择文本分类', trigger: 'change' }
                ],
                lookScope: [
                    { required: true, message: '请选择文本可见范围', trigger: 'change' }
                ]
            }
        }
    },
    methods: {
        async handleImgAdd(pos, $file) {
            var formdata = new FormData();
            formdata.append('article', $file);
            await articleApi.uploadFile(formdata).then(res => {
                this.$refs.md.$img2Url(pos, res.data)
            })
        },
        openDialog(status) {
            this.article.publishStatus = status
            this.getDigest()
            this.dialogFormVisible = true
        },

        handleAvatarSuccess(res, file) {
            this.$set(this.article, 'cover', res.data)
            this.$message.success("上传成功！")
        },

        // 获取摘要
        getDigest() {
            const regex = /^(#+)\s*(.+)\s*([\s\S]*?)(?=(#+\s*|$))/gm;

            // 存储提取的标题和正文
            const sections = [];

            let match;
            while ((match = regex.exec(this.article.content)) !== null) {
                const level = match[1].length;
                const title = match[2];
                const content = match[3].trim();
                sections.push({ level, title, content });
            }

            let text = '';
            // 输出提取的标题和正文
            for (const { title, content } of sections) {
                text += `${title}: ${content}` + ';'
            }
            this.article.digest = text
        },

        // 提交表单
        async submitFrom() {
            debugger
            if (!this.article.title || !this.article.lookScope || !this.article.type || !this.article.content) {
                this.$message.error('标题/范围/分类/内容皆不可为空哦！！');
                return
            }

            await articleApi.addArticle(this.article).then(res => {
                this.$message({
                    message: '发布成功',
                    type: 'success'
                });
                this.dialogFormVisible = false
            })
        },
        // 获取文章可见范围
        getLookScope(code) {
            dict.getBlogDictByCode(code).then(res => {
                this.lookScopeList = res.data
            })
        },
        // 获取文章类型
        getArticleType(code) {
            dict.getBlogDictByCode(code).then(res => {
                this.articleTypeList = res.data
            })
        },
    },
    mounted() {

        // 获取文章可见范围
        this.getLookScope('reception_article_scope');
        // 获取文章类型
        this.getArticleType('reception_article_type');

    }
}
</script>

<style scoped>
::-webkit-scrollbar-track {
    background-color: white;
}
.el-header {
    padding: 0;
    position: sticky;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 9999;
    /* box-shadow: 0px 10px 20px 0px rgba(0, 0, 30, 0.7); */
}

::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 160px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}

.avatar {
    width: 160px;
    height: 100px;
    display: block;
}

.el-button {
    margin-top: 5px !important;
}

::v-deep .addArticel .el-col {
    border-right: 1px solid #c0c4cc;
}

.buttonDiv {
    vertical-align: middle;
}

.el-row {
    background-color: white;
    border: 1px solid #c0c4cc;
}

::v-deep .blog-titel .el-input__inner {
    border: none !important;
    border-radius: 0;
    height: 50px;
    line-height: 50px;
}


.el-header,
.el-footer {
    padding: 0;
}

.el-main {
    height: 91.8vh;
    backdrop-filter: blur(10px);
    padding: 0;
    overflow: hidden;
}


.markdown-body {
    height: 92.6%;
    border-radius: 0;
    box-shadow: none !important;
}

::v-deep .v-note-wrapper.fullscreen {
    z-index: 2100;
}
</style>